package routers

import (
	. "gddgame.cc/galaxy/common/dsl/web"
	app "gddgame.cc/galaxy/core/controllers/app"
	"gddgame.cc/galaxy/server/composer"
	"gddgame.cc/galaxy/server/web"
)

func AppAuth(context web.Context) bool {
	appKey := context.Header("appKey")
	noise := context.Header("noise")
	sign := context.Header("sign")

	app, err := app.ValidSign(context, appKey, noise, sign)
	if err != nil {
		return false
	}
	if err := context.Set("appId", app.Id); err != nil {
		return false
	}
	return true
}

func AppHandler(path string, builder composer.Builder, router web.Router) error {
	if err := app.InitApp(builder, builder); err != nil {
		return err
	}
	r := NewSwaggerRouter(path, builder, router, &SwaggerRouterConfig{
		Info: SwaggerInfo{
			Title: "",
		},
	})
	web.TrackRestful(router, "trackId")
	r.Use(MultiAuthMiddle(nil, AppAuth))

	r.Router.Post("/token/generate", Controller([]Param{
		{Name: "appId", In: Cache},
		{Name: "openId", In: Body},
		{Name: "policy", In: Body},
		{Name: "expire", In: Body, Type: Int},
	}, app.GenerateAccessToken))

	r.Group("/user")
	return nil
}
